package com.example.common.utils;

import lombok.SneakyThrows;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;

/**
 * @author longchengyang
 * date 2021-05-12
 */
public class WillingAESUtils {


    //参数分别代表 算法名称/加密模式/数据填充方式
    private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";
    private static final String AES_KEY = "WillingTEST12345";

    /**
     * 加密
     *
     * @param content    加密的字符串
     * @param encryptKey key值
     * @return
     * @throws Exception
     */
    public static String encrypt(String content, String encryptKey) throws Exception {
        if (content == null) {
            return null;
        }
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), "AES"));
        byte[] b = cipher.doFinal(content.getBytes("utf-8"));
        // 采用base64算法进行转码,避免出现中文乱码
        return replace(Base64.encodeBase64String(b));
    }

    /**
     * 解密
     *
     * @param encryptStr 解密的字符串
     * @param decryptKey 解密的key值
     * @return
     * @throws Exception
     */
    public static String decrypt(String encryptStr, String decryptKey) throws Exception {
        if (encryptStr == null) {
            return null;
        }
        encryptStr = deReplace(encryptStr);
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES"));
        // 采用base64算法进行转码,避免出现中文乱码
        byte[] encryptBytes = Base64.decodeBase64(encryptStr);
        byte[] decryptBytes = cipher.doFinal(encryptBytes);
        return new String(decryptBytes);
    }

    public static String encrypt(String content) throws Exception {
        return encrypt(content, AES_KEY);
    }

    @SneakyThrows
    public static String encryptObj(Object obj) {
        if (obj == null) {
            return null;
        }
        String content = String.valueOf(obj);
        return encrypt(content, AES_KEY);
    }

    public static String decrypt(String encryptStr) throws Exception {
        return decrypt(encryptStr, AES_KEY);
    }

    /**
     * 加密方法
     *
     * @param sourceStr   源数据
     * @param encryptType 加密类型
     * @return
     */
    public static String digest(String sourceStr, String encryptType) {
        char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            byte[] btInput = sourceStr.getBytes();
            // 获得MD5摘要算法的MessageDigest对象
            MessageDigest mdInst = MessageDigest.getInstance(encryptType);
            // 使用指定的字节更新摘要
            mdInst.update(btInput);
            // 获得密文
            byte[] md = mdInst.digest();
            // 将密文转换成十六进制的字符串形式
            int j = md.length;
            char[] str = new char[j * 2];
            int k = 0;
            for (byte byte0 : md) {
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            return sourceStr;
        }
    }

    private static String replace(String raw){
        return raw.replace("+", "-").replace("/", "_").replace("=","");
    }

    private static String deReplace(String raw){
        return raw.replace("-", "+").replace("_", "/");
    }
}
